package com.doit.day01;

import org.apache.commons.lang3.RandomUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.ArrayList;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 每隔5s，就返回一次被选英雄前3的英雄
 */
public class _05_英雄出场TOPN {
    public static void main(String[] args) throws InterruptedException {

        Jedis jedis = new Jedis("linux01", 6379);
        //选value的数据类型 sorted set
        //这个线程在不断得选择英雄，然后往hero这个集合中放
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<String> list = new ArrayList<>();
                list.add("诺手");
                list.add("德莱文");
                list.add("卡莎");
                list.add("无E烦");
                list.add("瞎子");
                list.add("托儿所");
                list.add("儿童劫");
                list.add("奥巴马");
                list.add("女枪");
                list.add("寒冰");
                list.add("轮子妈");
                list.add("女警");

                while (true){
                    int index = RandomUtils.nextInt(0, list.size());
//                    System.out.println(list.get(index)+"  hero is coming ......");
                    //往里面去添加元素，添加的时候，如果这个英雄出现过，那么他的score分数就要依次加一
                    jedis.zincrby("hero",1,list.get(index));
                    try {
                        Thread.sleep(RandomUtils.nextInt(100,250));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        //准实时
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Set<Tuple> hero = jedis.zrevrangeWithScores("hero", 0, 2);

                for (Tuple tuple : hero) {
                    String element = tuple.getElement();
                    double score = tuple.getScore();
                    System.out.println("当前的时间戳是："+System.currentTimeMillis()+"==》结果是"+element+","+score);
                }
            }
        },10000,5000);


    }
}
